"""
验证通过用户名获取个人空间ID的功能

根据IAM API文档实现:
1. 通过用户名获取用户信息
2. 获取用户的个人空间ID
"""

import sys
import os

from fastapi.background import P
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dotenv import load_dotenv
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient

load_dotenv()
def get_user_info(username: str):
    """
    通过用户名获取用户信息

    Action: GetUser
    参数:
        - Name: 用户名
    """
    print(f"\n=== Step 1: Getting user info for username: {username} ===")

    client = HiAgentAPIClient()
    print(client.config.ACCESS_KEY)
    # 调用GetUser接口
    payload = {
        "Name": username
    }

    try:
        response = client.call_iam_api("GetUser", payload)

        # 检查响应格式
        if isinstance(response, dict):
            # 可能直接返回User对象
            if response.get("ID"):
                user = response
                print(f"User found:")
                print(f"  - UserID: {user.get('ID')}")
                print(f"  - UserName: {user.get('UserName')}")
                print(f"  - DisplayName: {user.get('DisplayName')}")
                print(f"  - TenantID: {user.get('TenantID')}")
                return user
            # 或者在Result.User中
            elif response.get("User"):
                user = response["User"]
                print(f"User found:")
                print(f"  - UserID: {user.get('ID')}")
                print(f"  - UserName: {user.get('UserName')}")
                print(f"  - DisplayName: {user.get('DisplayName')}")
                print(f"  - TenantID: {user.get('TenantID')}")
                return user

        print(f"User not found")
        print(f"Response: {response}")
        return None
    except Exception as e:
        print(f"Error getting user info: {e}")
        return None


def get_personal_workspace(user_id: str):
    """
    通过用户ID获取个人空间

    根据文档,个人空间的特点:
    1. IsPersonal = True
    2. OwnerID = UserID

    使用ListWorkspace API查询
    """
    print(f"\n=== Step 2: Getting personal workspace for user: {user_id} ===")

    client = HiAgentAPIClient()

    # 列出所有工作空间,然后筛选个人空间
    payload = {
        "ListOpt": {
            "PageNumber": 1,
            "PageSize": 100
        }
    }

    try:
        response = client.call_iam_api("ListWorkspace", payload)

        # 检查响应格式
        workspaces = None
        if isinstance(response, dict):
            if response.get("Items"):
                workspaces = response["Items"]
            elif response.get("Result") and response["Result"].get("Items"):
                workspaces = response["Result"]["Items"]

        if workspaces:
            # 筛选个人空间
            for workspace in workspaces:
                if workspace.get("OwnerID") == user_id:
                    print(f"Personal workspace found:")
                    print(f"  - WorkspaceID: {workspace.get('ID')}")
                    print(f"  - WorkspaceName: {workspace.get('Name')}")
                    print(f"  - OwnerID: {workspace.get('OwnerID')}")
                    print(f"  - IsPersonal: {workspace.get('IsPersonal', False)}")
                    return workspace

            print(f"No personal workspace found for user {user_id}")
            return None
        else:
            print(f"Failed to list workspaces")
            print(f"Response: {response}")
            return None
    except Exception as e:
        print(f"Error getting workspace: {e}")
        return None


def get_workspace_by_name(workspace_name: str):
    """
    通过工作空间名称获取工作空间详情

    Action: GetWorkspace
    """
    print(f"\n=== Alternative: Getting workspace by name: {workspace_name} ===")

    client = HiAgentAPIClient()

    payload = {
        "Name": workspace_name
    }

    response = client.call_iam_api("GetWorkspace", payload)

    if response.get("Result") and response["Result"].get("Item"):
        workspace = response["Result"]["Item"]
        print(f"Workspace found:")
        print(f"  - WorkspaceID: {workspace.get('ID')}")
        print(f"  - WorkspaceName: {workspace.get('Name')}")
        print(f"  - OwnerID: {workspace.get('OwnerID')}")
        return workspace
    else:
        print(f"Workspace not found")
        print(f"Response: {response}")
        return None


def main():
    """
    主函数: 演示如何通过用户名获取个人空间ID
    """
    print("=" * 60)
    print("Verify: Get Personal Workspace ID by Username")
    print("=" * 60)

    # 测试用户名
    username = "2013000032"

    # Step 1: 获取用户信息
    user = get_user_info(username)

    if not user:
        print("\nFailed to get user information")
        return

    user_id = user.get("ID")

    # Step 2: 获取个人空间
    workspace = get_personal_workspace(user_id)

    if workspace:
        print("\n" + "=" * 60)
        print("SUCCESS: Personal workspace found!")
        print(f"Username: {username}")
        print(f"UserID: {user_id}")
        print(f"WorkspaceID: {workspace.get('ID')}")
        print("=" * 60)
    else:
        print("\n" + "=" * 60)
        print("FAILED: Personal workspace not found")
        print("=" * 60)

    # 备选方案: 如果个人空间名称就是用户名
    # workspace_alt = get_workspace_by_name(username)


if __name__ == "__main__":
    main()
